package db

import (
	"database/sql"
	"fmt"
	"git.sr.ht/~mil/mobroute/src/logger"
	"git.sr.ht/~mil/mobroute/src/utilfuncs"
	"strconv"
	"strings"
)

// QueryBoundsMatch is a querying function that determines if the passed
// param matches for the mdbid for the DB conneciton min/max lat/lon
func (c *DBConnection) QueryBoundsMatch(coord utilfuncs.Coord) error {
	var (
		query = fmt.Sprintf(
			`
				select count(*) from (
					select 
						(? between min_lat and max_lat) and
						(? between min_lon and max_lon) as matches_bounds
					from _vsources
					where mdbid in (%s) and matches_bounds
				) g
			`,
			strings.Join(utilfuncs.ArrayWithValue(len(c.QuerySources), "?"), ","),
		)
		params = append(
			[]any{coord.Lat, coord.Lon},
			utilfuncs.Anyify(utilfuncs.ArrayIntToArryString(c.QuerySources))...,
		)
	)

	if value, err := c.QueryValue(query, params); err != nil {
		return err
	} else if value == "" {
		return fmt.Errorf("%v doesn't match any of the provided bounds", coord)
	} else if matches, err := strconv.Atoi(value); err != nil {
		return err
	} else if matches < 1 {
		return fmt.Errorf("%v doesn't match any of the provided bounds - matches: %d, check bounds for sources: %v", coord, matches, c.QuerySources)
	} else {
		return nil
	}
}

func (c *DBConnection) QueryValue(query string, args []any) (string, error) {
	var val string
	logger.Warnf("Running query: %v with args: [%v]", query, args)
	if err := c.DB.QueryRow(query, args...).Scan(&val); err != nil && err != sql.ErrNoRows {
		return "", err
	} else {
		return val, nil
	}
}
